//
//  MGReceiptSwitchView.m
//  MoneyGoal_iOS
//
//  Created by yyb on 2022/7/24.
//  Copyright © 2022 Moneyease CO,. LTD. All rights reserved.
//

#import "MGReceiptSwitchView.h"
#import "MGReceiptSwitchCell.h"

@implementation MGReceiptSwitchView

- (instancetype)init {
    self = [super init];
    if (!self) return nil;
    
    self.gatherView = [UICollectionView createAtSuperView:self delegeteTarget:self edgeInsets:UIEdgeInsetsZero scrollDirection:UICollectionViewScrollDirectionHorizontal constraintBlock:^(MASConstraintMaker *make) {
        make.edges.equalTo(self);
    } dequeueCellIdentifiers:@[@"MGReceiptSwitchCell"] configureBlock:^(UICollectionView *view, UICollectionViewFlowLayout *layout) {
        layout.minimumLineSpacing = 0;
        layout.minimumInteritemSpacing = 0;
    }];
    
    self.wrapperView = [UIView createViewAtSuperView:self backgroundColor:[APP_COLOR_MAIN colorWithAlphaComponent:0.6] constraintBlock:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(35, 5));
        make.bottom.equalTo(self).offset(-10);
        make.left.equalTo(self);
    } configureBlock:nil];
    
    return self;
}

- (void)handleChangeReceiptType {
    [self.gatherView reloadData];
    [self handleWrapper];
}

- (void)handleWrapper {
    NSInteger index = 0;
    if (self.getSelectTypeBlock) {
        index = self.getSelectTypeBlock();
    }
    
    CGFloat itemWidth = 120 / 2;
    CGFloat x = (itemWidth - 35) / 2 + itemWidth * index;
    
    [UIView animateWithDuration:0.2 animations:^{
        self.wrapperView.transform = CGAffineTransformMakeTranslation(x, 0);
    }];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return 2;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake(120 / 2, 40);
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    MGReceiptSwitchCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MGReceiptSwitchCell" forIndexPath:indexPath];
    
    NSString *text = nil;
    if (indexPath.row == 0) {
        text = @"支出";
    } else if (indexPath.row == 1) {
        text = @"收入";
    }
    
    BOOL isSelect = NO;
    if (self.getSelectTypeBlock) {
        isSelect = indexPath.row == self.getSelectTypeBlock();
    }
    
    [cell configViewWithTitleValue:text status:isSelect];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (self.receiptTypeSelectBlock) {
        self.receiptTypeSelectBlock(indexPath.row);
    }
    
    [collectionView reloadData];
    [self handleWrapper];
}

@end
